extends Node2D

const POINTS:=8

@onready var arrow:Area2D=$Arrow
@onready var curve:Line2D=$CanvasLayer/Curve

var currentCard:Card
var hasTaget:=false

func _ready():	
	Events.cardAimStarted.connect(onCardAimStart)
	Events.cardAimEnded.connect(onCardAimEnd)

func _physics_process(_delta):
	if !hasTaget:return
	arrow.position=get_local_mouse_position()
	curve.points=_get_points()

# 计算点位
func _get_points()->Array:
	var points := []
	var start:=currentCard.global_position
	start.x+=currentCard.size.x/2
	var arrowPos:=get_local_mouse_position()
	var distance:=arrowPos-start

	for i in range(POINTS):
		# 计算权重
		var t:=(1.0/POINTS)*i
		var x:=start.x+distance.x*t
		var y:=start.y + ease_out_cubic(t)*distance.y
		points.append(Vector2(x,y))
	points.append(arrowPos)
	return points

# 曲线函数
func ease_out_cubic(num:float)->float:
	return 1.0-pow(1.0-num,3.0)

# 瞄准开始
func onCardAimStart(card:Card)->void:
	if !card.cardSrc.isSingle():return

	hasTaget=true
	arrow.monitoring=true
	arrow.monitorable=true
	currentCard=card

# 瞄准结束
func onCardAimEnd(card:Card)->void:
	if currentCard!=card:return push_error('退出瞄准的卡牌不一致')

	hasTaget=false
	curve.clear_points()
	arrow.position=Vector2.ZERO
	arrow.monitoring=false
	arrow.monitorable=false
	currentCard=null

# 监控箭头进入区域的信号
func _on_arrow_area_entered(area:Area2D):
	if !currentCard or !hasTaget:return
	if currentCard.placeArea!=area:
		currentCard.placeArea=area

func _on_arrow_area_exited(_area:Area2D):
	if !currentCard or !hasTaget:return
	currentCard.placeArea=null

